<template>
<div class="container">
    <header class="header">
        <div class="header-content">
            <div class="header-left">
                <a href="#" @click="GoBack()" class="back-btn">
                    <svg t="1751614585251" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" 
                        p-id="1471" width="20" height="20">
                        <path d="M790.865959 73.216062 322.123178 512.062492l468.74278 438.746442c16.397998 16.697962 16.397998 43.894642 0 60.592603-16.397998 16.697962-42.894764 16.697962-59.292762 0l-498.839107-466.943c-8.698938-8.898914-12.398487-20.797461-11.898548-32.496033-0.599927-11.698572 3.099622-23.497132 11.898548-32.496033l498.839107-466.943c16.397998-16.697962 42.894764-16.697962 59.292762 0C807.263957 29.421409 807.263957 56.518101 790.865959 73.216062z" 
                            fill="#272636" 
                            p-id="1472">
                        </path>
                    </svg>
                </a>
                <div class="header-title">我的回复</div>
            </div>
        </div>
    </header>

    <main class="main-content">
        <!-- 标签切换 -->
        <div class="content-tabs fixed-tabs">
            <div class="tab active">
                回复我的
            </div>
        </div>

        <!-- 列表内容 -->
        <div class="list-container">
            <!-- 回复我的 -->
            <div class="reply-list">
                <!-- 列表内容 -->
                <div v-for="reply in replyList" :key="reply.id" class="reply-item" @click="goToPostDetail(reply.postId)">
                    <div class="reply-avatar" @click.stop="goToUserProfile(reply.userId)" :style="{ backgroundImage: reply.userAvatarUrl && reply.userAvatarUrl.trim() ? `url(${reply.userAvatarUrl.replace(/`/g, '')})` : '' }">
                        {{ reply.userAvatarUrl && reply.userAvatarUrl.trim() ? '' : reply.username?.charAt(0) }}
                    </div>
                    <div class="reply-content">
                        <div class="reply-header">
                            <div class="user-name">{{ reply.username }}</div>
                            <div class="reply-time">{{ formatTime(reply.createTime) }}</div>
                        </div>
                        <div class="reply-text">{{ reply.content }}</div>
                        <div class="original-post">
                            <div class="post-preview">我的评论: {{ reply.myContent || '查看原帖' }}</div>
                        </div>
                    </div>
                </div>

                <!-- 视图监听盒子 -->
                <div ref="viewFlagBox_replies" :style="{ paddingTop: replyList.length < 1 ? '20px' : '0px' }">
                    <div v-if="!isHasMoreReplies && !isLoadingReplies" 
                        style="height: 30px;display: flex;justify-content: center;font-size: 12px;color: #61666D;">
                        没有更多回复
                    </div>
                    <div v-else
                        style="height: 30px;display: flex;justify-content: center;font-size: 12px;color: #61666D;">
                        努力加载中
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import 'vant/lib/toast/style'
import api from '@/api/index.js'
import { UserInfoStore } from '@/stores/userInfoStore'
import { TipStore } from '@/stores/tipStore'
import { formatTime } from '@/utils/format.js'

const router = useRouter()
const user_Store = UserInfoStore()
const tip_Store = TipStore()

// #region 辅助方法
// 返回
function GoBack() {
    router.go(-1)
}

// 跳转到帖子详情
function goToPostDetail(postId) {
    router.push({
        name: 'OpusDetail',
        query: { id: postId }
    })
}

// 跳转用户个人主页
function goToUserProfile(uid) {
    router.push({
        name: 'UserProfile',
        query: { uid: uid }
    })
}
// #endregion


// 回复我的相关数据和方法
const pageNum_replies = ref(1)
const pageSize_replies = ref(10)
const isLoadingReplies = ref(false)
const isHasMoreReplies = ref(true)
const replyList = ref([])

// 获取回复我的评论
const getReplyToMe = async() => {
    try {
        isLoadingReplies.value = true
        const res = await api.Comment_GetReplyToMe(
            pageNum_replies.value,
            pageSize_replies.value
        )
        
        if (res && res.data && res.data.code === 1) {
            const newReplies = res.data.data.list || []
            
            // 如果是第一页，直接替换数据；否则追加数据
            if (pageNum_replies.value === 1) {
                replyList.value = newReplies
            } else {
                replyList.value = [...replyList.value, ...newReplies]
            }
            
            // 判断是否还有更多数据
            // 根据返回的总数和当前已加载数量判断
            const totalCount = parseInt(res.data.data.total) || 0
            isHasMoreReplies.value = replyList.value.length < totalCount
            
        } else {
            tip_Store.errorTip(res?.data?.msg || '获取回复失败')
        }
    } catch (error) {
        console.error('获取回复我的评论失败:', error)
        tip_Store.errorTip('获取回复失败，请稍后重试')
    } finally {
        isLoadingReplies.value = false
    }
}

// 加载更多数据
async function loadMoreData() { 
    if(isHasMoreReplies.value===false || isLoadingReplies.value===true){ return }
    console.log('加载更多回复数据！')
    pageNum_replies.value += 1 // 下一页
    try {
        await getReplyToMe()
    } catch (error) {
        // 如果加载失败，恢复页码
        pageNum_replies.value -= 1
    }
}

// 视图监听相关
const viewFlagBox_replies = ref(null);
let observer = null;

function observerViewFlagBox(){
    observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                console.log('进入视图!!!');
                loadMoreData()
            }
        });
    }, {
        threshold: 0,
        rootMargin: '0px'
    });

    if (viewFlagBox_replies.value) {
        observer.observe(viewFlagBox_replies.value);
    }
}

onMounted(async()=>{
    await getReplyToMe() // 初始化获取回复我的评论
    nextTick(() => {
        observerViewFlagBox() // 设置视图监听
    })
})
</script>

<style lang="scss" scoped>
.container {
    background-color: #f8f8f8;
    min-height: 100vh;
}

/* 头部样式 */
.header {
    background: white;
    padding: 15px 20px;
    box-shadow: 0 1px 5px rgba(0,0,0,0.05);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    max-width: 800px;
    margin: 0 auto;
}

.header-left {
    display: flex;
    align-items: center;
}

.back-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    text-decoration: none;
}

.header-title {
    font-size: 18px;
    font-weight: 500;
    color: #333;
}

/* 主内容样式 */
.main-content {
    margin-top: 54px;
    background: #f8f8f8;
    min-height: calc(100vh - 60px);
}

/* 标签切换样式 */
.content-tabs {
    display: flex;
    background: white;
    padding: 0 20px;
    box-shadow: 0 1px 5px rgba(0,0,0,0.05);
}

.fixed-tabs {
    position: sticky;
    top: 54px;
    z-index: 90;
}

.tab {
    flex: 1;
    text-align: center;
    padding: 15px 0;
    font-size: 16px;
    color: #666;
    cursor: pointer;
    position: relative;
    transition: all 0.2s;
}

.tab.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 25%;
    width: 50%;
    height: 3px;
    background: #ff6b6b;
    border-radius: 3px;
}

/* 列表容器样式 */
.list-container {
    padding: 10px 0;
}

/* 回复项样式 */
.reply-item {
    display: flex;
    padding: 15px;
    background: white;
    margin-bottom: 10px;
    cursor: pointer;
    transition: background-color 0.2s;
}

.reply-item:hover {
    background-color: #f9f9f9;
}

.reply-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: bold;
    margin-right: 12px;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    flex-shrink: 0;
}

.reply-content {
    flex: 1;
    min-width: 0;
}

.reply-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
}

.user-name {
    font-weight: 500;
    color: #333;
    font-size: 14px;
}

.reply-time {
    font-size: 12px;
    color: #999;
}

.reply-text {
    font-size: 14px;
    color: #333;
    line-height: 1.4;
    margin-bottom: 8px;
    word-break: break-word;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    line-clamp: 2;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.original-post {
    background-color: #f5f5f5;
    padding: 8px;
    border-radius: 4px;
    margin-top: 8px;
}

.post-preview {
    font-size: 13px;
    color: #666;
    line-height: 1.3;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    line-clamp: 2;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}
</style>
